<?php

class SerialController extends BaseController {
	/*
	 * controller 魔术方法，此方法不可少
	 */
	function __construct() {
		parent::__construct();
	}

	function actionIndex($get) {
		$serial = KJ::M('Serialnumber');
		$pageData = array();

		if(isset($_POST['register']) && !empty($_POST)) {
			$machineCode = $serial->replaceSWord(implode('-', $this->dealSpace($_POST['register']['machineCode'])));
			$snCode = $serial->replaceSWord(implode('-', $this->dealSpace($_POST['register']['snCode'])));

			// 正则验证序列号合法性
			if(!$serial->validateCode($snCode)) {
				$pageData['error'] = '请填写正确的序列号';
				goto end;
			}

			// 正则验证机器码合法性
			if(!$serial->validateCode($machineCode)) {
				$pageData['error'] = '请填写正确的机器码';
				goto end;
			}

			// 查看序列号是否有效
			$snRes = $serial->validateSerial($snCode);
			if($snRes === 0) {
				$pageData['error'] = '错误的序列号';
				goto end;	
			} else if($snRes === 1) {
				$pageData['error'] = '无效的序列号';
				goto end;
			}

			// 如果机器码使用过，提示
			if($serial->validateMachine($machineCode)) {
				$pageData['error'] = '无效的序列号';
				goto end;
			}

			// 获取注册码，并去注册
			if($zhucema = $serial->getRegCode($snCode, $machineCode)) {
				$updateData = array(
					'jiqima' => $machineCode,
					'zhucema' => $zhucema,
					'status' => $serial::STATUS_USED,
					'registerd_at' => date('Y-m-d H:i:s'),
				);
				if($serial->where('xuliehao = "'.$snCode.'" AND status = "'.$serial::STATUS_INIT.'"')->update($updateData)) {
					$pageData['message'] = '注册成功:'.$zhucema;
					$pageData['zhucema'] = $zhucema;
					$pageData['snCode'] = $snCode;
				}
			}
		}

		end:
		// 如果是ajax输出，直接输出json结构
		if($this->isAjaxRequest()) {
			$this->echoAjax($pageData);
		}

		$this->assign($pageData);
		$this->display();
	}


	function echoAjax($data) {
		$frame = array(
			'state' => 0,
			'message' => $data['error'],
			'data' => null,
		);

		if(isset($data['snCode'])) {
			$frame['state'] = 1;
			$frame['message'] = $data['message'];
			$serial = KJ::M('Serialnumber');
			$data = $serial->fields('id, xuliehao sn, jiqima machine, year, zhucema reg')->where('xuliehao = "'.$data['snCode'].'"')->getOne();

			$frame['data'] = $data;
		}

		$jsonStr = json_encode($frame);

		// 如果是跨域，就以跨域形式输出
		if(isset($_GET['callback'])) {
			$jsonStr = $_GET['callback'].'('.$jsonStr.')';
		}

		echo $jsonStr;
		die();
	}

	function dealSpace($data) {
		return array_map(function($value) {
			return trim($value, '　 ');
		}, $data);
			
	}
}